package com.jie.demo1.controller.loginController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jie.demo1.Sservice.UserService;
import com.jie.demo1.common.ulity.JWTUtil;
import com.jie.demo1.common.ulity.securityUtil;
import com.jie.demo1.pojo.Result;
import com.jie.demo1.pojo.User;

import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//用于登陆等相关的接口
@RestController
@RequestMapping("/login")
@CrossOrigin(origins = "http://localhost:5173/")  //开启跨域请求
public class loginController {
    @Resource
    private UserService userService;
    //测试接口
    @PostMapping("/parseToken")
    public Result<String> parseToken(@RequestHeader("Authorization") String authorization) {

        System.out.println("请求头获取");
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            return Result.fail(301,"请求头报错");
        }

        //因为上面的token会有一个长度为7的前缀，这里直接从第八个开始获取，表示只获取token信息
        String token = authorization.substring(7);
        System.out.println("Token: " + token);
        try {
            Claims claims = JWTUtil.checkToken(token);
            String username = claims.get("username", String.class);
            return Result.ok(username);
        } catch (Exception e) {
            return Result.fail(302,"无效token: " + e.getMessage());
        }
    }




    //登陆接口
    @PostMapping("/default")
    public Result<String> login(@RequestBody User user){
        String no = user.getNo();
        String password = user.getPassword();
        //通过加密的方式将密码单向加密如何去对比数据库内容
        password = securityUtil.md5Hex(password);
        System.out.println(no);
        //创建wapper对象来判断是否是数据库中的对象
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getNo,no).eq(User::getPassword,password);
        List<User> list = userService.list(userWrapper);

        if (list != null &&!list.isEmpty()) {
                //将list的内容赋值给user对象
            user = list.get(0);
            System.out.println(user);
                //创建token，调用JWTUtil类中的createToken方法
            String token = JWTUtil.createToken(user.getNo(), user.getName());
                //将token返回给前端
            System.out.println(token);
            return Result.ok(token);
        }
        return Result.fail(307,"账号密码错误");
}

}
